import sqlite3


def db_connection(db_path=":memory:"):
    """数据库连接装饰器"""
    def decorator(func):
        def wrapper(*args, **kwargs):
            # 创建数据库连接
            conn = sqlite3.connect(db_path)
            try:
                # 把连接作为参数传给原函数
                result = func(conn,*args, **kwargs)
                conn.commit()
                return result
            except Exception as e:
                conn.rollback()
                raise
            finally:
                conn.close()
        return wrapper
    return decorator


# 使用装饰器
@db_connection("example.db")
def create_user(conn,name,email):
    """创建用户"""
    cursor = conn.cursor()
    cursor.execute("""
    create table if not exists users(
        id integer primary key,
        name text not null,
        email text unique not null
    )
    """)
    cursor.execute("insert into users(name,email) values (?,?)", (name,email))
    return cursor.lastrowid

@db_connection("example.db")
def get_user(conn,user_id):
    """获取用户"""
    cursor = conn.cursor()
    cursor.execute("select * from users where id = ?", (user_id,))
    return cursor.fetchone()

# 测试
user_id = create_user("张三","zhangsan@example.com")
user = get_user(user_id)
print(f"创建的用户：{user}")